package ift604.projet.oauth;

import ift604.projet.stereomood.Constants;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

// fenetre web permettant de se logger a un site utilisant l'oauth
public class OAuthLoginActivity extends Activity {
	public static OAuthManager oAuthManager;
	
	final String TAG = getClass().getName();
	
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        Log.i(TAG, "Starting task to retrieve request token.");
		new OAuthRequestTokenTask(oAuthManager.consumer, oAuthManager.provider).execute();
	}

	/**
	 * Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
	 * The callback URL will be intercepted here.
	 */
	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent); 
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		final Uri uri = intent.getData();
		if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
			Log.i(TAG, "Callback received : " + uri);
			Log.i(TAG, "Retrieving Access Token");
			new RetrieveAccessTokenTask(oAuthManager.consumer, oAuthManager.provider, prefs).execute(uri);
			finish();	
		}
	}
	
	public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
		final String TAG = getClass().getName();
		private OAuthProvider provider;
		private OAuthConsumer consumer;

		public OAuthRequestTokenTask(OAuthConsumer consumer, OAuthProvider provider) {
			this.consumer = consumer;
			this.provider = provider;
		}

		/**
		 * 
		 * Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
		 * 
		 */
		@Override
		protected Void doInBackground(Void... params) {
			
			try {
				final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
				startActivity(intent);
			} catch (Exception e) {
				if (OAuthLoginActivity.oAuthManager != null) {
					runOnUiThread(new Runnable() {
	                    public void run() {
	                    	OAuthLoginActivity.oAuthManager.authenticationFailure();
	                    }
	                });
				}

				finish();
			}

			return null;
		}

	}
	
	public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
		private OAuthProvider provider;
		private OAuthConsumer consumer;
		private SharedPreferences prefs;
		
		public RetrieveAccessTokenTask(OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
			this.consumer = consumer;
			this.provider = provider;
			this.prefs=prefs;
		}


		/**
		 * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret 
		 * for future API calls.
		 */
		@Override
		protected Void doInBackground(Uri...params) {
			final Uri uri = params[0];
			final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
			
			final OAuthManager oauth = oAuthManager;

			try {
		        provider.setOAuth10a(true);  // set a false pour une raison que j'ignore, mais doit etre a true pour envoyer notre request token
				provider.retrieveAccessToken(consumer, oauth_verifier);

				final Editor edit = prefs.edit();
				edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
				edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
				edit.commit();
				
				String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
				String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
				
				consumer.setTokenWithSecret(token, secret);

				if (oauth != null) {
                   	oauth.authenticationSuccess();
				}
				
				Log.i(TAG, "OAuth - Access Token Retrieved");
				
			} catch (Exception e) {
				if (oauth != null) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                        	oauth.authenticationFailure();
                        }
                    });
				}

				Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
			}

			oAuthManager = null;

			return null;
		}


	}	
	
}